package com.jincheng.web.controller.system;

import com.jincheng.common.annotation.Log;
import com.jincheng.common.constant.CacheConstants;
import com.jincheng.common.constant.Constants;
import com.jincheng.common.core.controller.BaseController;
import com.jincheng.common.core.domain.AjaxResult;
import com.jincheng.common.core.page.TableDataInfo;
import com.jincheng.common.core.redis.RedisCache;
import com.jincheng.common.enums.BusinessType;
import com.jincheng.common.utils.poi.ExcelUtil;
import com.jincheng.common.utils.uuid.IdUtils;
import com.jincheng.system.domain.Activity;
import com.jincheng.system.domain.dto.ActivityDetailDTO;
import com.jincheng.system.domain.dto.ActivityScreenDTO;
import com.jincheng.system.domain.dto.ActivitySimpleDTO;
import com.jincheng.system.service.IActivityService;
import com.jincheng.system.service.IQrCodeService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 活动模块
 *
 * @author DairyJay
 * @date 2024-12-21
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/activity")
public class ActivityController extends BaseController {

    private final IActivityService activityService;
    private final IQrCodeService qrCodeService;
    private final RedisCache redisCache;


    /**
     * 查询活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/list")
    public TableDataInfo list(ActivityScreenDTO activityScreenDTO) {
        startPage();
        List<ActivityDetailDTO> list = activityService.selectActivitySimpleList(activityScreenDTO);
        return getDataTable(list);
    }

    /**
     * 查询活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/list/currentUser")
    public TableDataInfo listByUserId() {
        startPage();
        List<ActivitySimpleDTO> list = activityService.selectActivityListByUserId();
        return getDataTable(list);
    }

    /**
     * 查询当前用户的活动列表
     *
     * @param auditStatus 审核状态
     * @return 活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/listByAuditStatus/currentUser/{auditStatus}")
    public TableDataInfo listByCurrentUserAndAuditStatus(@PathVariable Integer auditStatus) {
        // 获取当前登录的用户id
        Long userId = getUserId();
        startPage();
        List<ActivitySimpleDTO> list = activityService.selectActivityListByUser(userId, auditStatus);
        return getDataTable(list);
    }

    /**
     * 查询当前用户的活动列表
     *
     * @param activityStatus 活动状态,0未开始.1进行中,2已结束
     * @return 活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/listByActivityStatus/currentUser/{activityStatus}")
    public TableDataInfo listByCurrentUserAndActivityStatus(@PathVariable Integer activityStatus) {
        // 获取当前登录的用户id
        Long userId = getUserId();
        startPage();
        List<ActivitySimpleDTO> list = activityService.selectActivityListByUserAndActivityStatus(userId, activityStatus);
        return getDataTable(list);
    }


    /**
     * 根据筛选条件查询活动列表
     *
     * @param activityScreenDTO 数据查询DTO
     * @return 活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/listByScreen")
    public TableDataInfo listByScreen(ActivityScreenDTO activityScreenDTO) {
        startPage();
        List<ActivityDetailDTO> list = activityService.selectActivityListByScreen(activityScreenDTO);
        return getDataTable(list);
    }

    /**
     * 根据部落id查询活动列表
     *
     * @param tribeId 部落id
     * @return 活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:list')")
    @GetMapping("/listByTribe/{tribeId}")
    public TableDataInfo listByTribe(@PathVariable Long tribeId) {
        ActivityScreenDTO activityScreenDTO = new ActivityScreenDTO();
        activityScreenDTO.setTribeId(tribeId);
        startPage();
        List<ActivityDetailDTO> list = activityService.selectActivitySimpleList(activityScreenDTO);
        return getDataTable(list);
    }

    /**
     * 获取活动统计信息
     */
    @GetMapping("/statistics")
    public AjaxResult statistics() {
        return success(activityService.getStatistics());
    }

    /**
     * 获取活动统计信息
     */
    @GetMapping("/statistics/heatmap/{year}")
    public AjaxResult getHeatMap(@PathVariable("year") Integer year) {
        return success(activityService.getHeatMap(year));
    }

    /**
     * 获取活动统计信息
     */
    @GetMapping("/statistics/pie/{type}")
    public AjaxResult getPie(@PathVariable("type") String type) {
        return success(activityService.getPie(type));
    }

    /**
     * 用户端获取活动统计信息
     */
    @GetMapping("/user/statistics")
    public AjaxResult userStatistics() {
        return success(activityService.getUserStatistics());
    }

    /**
     * 用户端获取活动统计信息
     */
    @GetMapping("/user/statistics/heatmap/{year}")
    public AjaxResult getUserHeatMap(@PathVariable Integer year) {
        return success(activityService.getUserHeatMap(year));
    }


    /**
     * 获取活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:activity:query')")
    @GetMapping(value = "/{activityId}")
    public AjaxResult getInfo(@PathVariable("activityId") Long activityId) {
        return success(activityService.selectActivityByActivityId(activityId));
    }

    /**
     * 获取活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:activity:query')")
    @GetMapping(value = "/getActivityDetail/{activityId}")
    public AjaxResult getActivityDetail(@PathVariable("activityId") Long activityId) {
        return success(activityService.selectActivityDetail(activityId));
    }

    /**
     * 报名活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:query')")
    @Log(title = "活动", businessType = BusinessType.INSERT)
    @GetMapping(value = "/apply/{activityId}")
    public AjaxResult apply(@PathVariable("activityId") Long activityId) {
        return activityService.apply(activityId, getLoginUser());
    }

    /**
     * 获取活动二维码
     */
    @PreAuthorize("@ss.hasPermi('system:activity:query')")
    @GetMapping("/qrcode/{activityId}")
    public AjaxResult getQrCode(@PathVariable("activityId") Long activityId,
                                @RequestParam("isSignInCode") boolean isSignInCode) {
        Long userId = getUserId();
        String uuid = IdUtils.simpleUUID();
        Map<String, Object> value = Map.of(
                "activityId", activityId,
                "chairId", userId,
                "isSignInCode", isSignInCode);
        String verifyKey = CacheConstants.QR_CODE_KEY + uuid;
        redisCache.setCacheObject(verifyKey, value, Constants.QR_EXPIRATION, TimeUnit.SECONDS);
        AjaxResult ajax = AjaxResult.success();
        String image = qrCodeService.createCodeToStream(uuid);
        ajax.put("img", image);
        return success(ajax);
    }


    /**
     * 导出活动列表
     */
    @PreAuthorize("@ss.hasPermi('system:activity:export')")
    @Log(title = "活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Activity activity) {
        List<Activity> list = activityService.selectActivityList(activity);
        ExcelUtil<Activity> util = new ExcelUtil<>(Activity.class);
        util.exportExcel(response, list, "活动数据");
    }


    /**
     * 新增活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:add')")
    @Log(title = "活动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Activity activity) {
        return toAjax(activityService.insertActivity(activity));
    }

    /**
     * 修改活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:edit')")
    @Log(title = "活动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Activity activity) {
        return toAjax(activityService.updateActivity(activity));
    }


    /**
     * 活动扫码签到/签退
     */
    @Log(title = "活动", businessType = BusinessType.UPDATE)
    @PutMapping("/signInOrOut/{verifyKey}")
    public AjaxResult signInOrOutByQrCode(@PathVariable String verifyKey) {
        return success(activityService.signInOrOutByQrCode(verifyKey, getUserId()));
    }

    /**
     * 活动定位签到/签退
     */
    @Log(title = "活动", businessType = BusinessType.UPDATE)
    @PutMapping("/signInOrOut")
    public AjaxResult signInOrOut(@RequestParam Boolean isSignIn, @RequestParam Long activityId) {
        return success(activityService.signInOrOut(getUserId(), isSignIn, activityId));
    }


    /**
     * 删除活动
     */
    @PreAuthorize("@ss.hasPermi('system:activity:remove')")
    @Log(title = "活动", businessType = BusinessType.DELETE)
    @DeleteMapping("/{activityIds}")
    public AjaxResult remove(@PathVariable Long[] activityIds) {
        return toAjax(activityService.deleteActivityByActivityIds(activityIds));
    }
}
